package org.lib93.com.libSkin

import android.app.Application
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import org.lib93.com.libSkin.lifecycle.ApplicationActivityLifecycle
import org.lib93.com.libSkin.utils.SkinPreference
import org.lib93.com.libSkin.utils.SkinResources
import java.util.*

class SkinManager private constructor(private val application: Application): Observable() { //集成Observable 将将自身设置为被观察者，一旦解析插件包成功 通知观察者 更换来自于插件包中的资源

    private val TAG = "TAG_SKINMANAGER"
    init{
        //初始化缓存工具类
        SkinPreference.getInstance(application)
        //初始化资源管理器
        SkinResources.getInstance(application)
        //注册activity声明周期回调 ApplicationActivityLifecycle
        application.registerActivityLifecycleCallbacks(ApplicationActivityLifecycle(this))
        //加载最后一次保存的皮肤
        //这里观察者还没有绑定成功
        loadSkin( SkinPreference.getInstance(application).getSkin())

    }

     fun loadSkin(skinPath:String?) {
        skinPath?.let {
            val packgerName = SkinResources.getInstance(application).initSkinResources(it)//初始化插件资源管理对象'
            packgerName?.let {
              SkinPreference.getInstance(application).setSkin(skinPath) //缓存当前的插件包路径
                //加载成功皮肤插件包后 通知观察者进行资源替换
                setChanged()
                notifyObservers()
            }?:let {
                Log.e(TAG, "解析插件包失败")
                return
            }

        }?:let {
            SkinPreference.getInstance(application).reset()
            SkinResources.getInstance(application).reset()
            setChanged()
            notifyObservers()
        }
    }
    companion object {
        @Volatile private var instance: SkinManager? = null
        fun getInstance(application: Application) =
            instance ?: synchronized(this) {
                instance ?: SkinManager(application).also { instance = it }
            }
    }
}